import React, { memo, useRef, useEffect, useState } from 'react'
import { ViewWrapper } from './style'
import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'

const ScrollView = memo((props) => {
  const scrollContentRef = useRef()
  // 只需要记录一次，不存在赋值
  let totalDistanceRef = useRef()
  const [showLeft, setShowLeft] = useState(false)
  const [showRight, setShowRight] = useState(false)
  const [posIndex, setPosIndex] = useState(0)

  useEffect(() => {
    // scrollContent实际宽度(含overhidden隐藏掉的部分)  clientWidth本身占据的宽度（能看见的部分）
    const { scrollWidth, clientWidth } = scrollContentRef.current
    const totalDistance = scrollWidth - clientWidth
    totalDistanceRef.current = totalDistance
    setShowRight(totalDistance > 0)
  }, [props.children])

  function handleTranslate(isRight){
    // 获取当前需要移动tab的索引及offsetLeft(距离scrollContent)
    const newIndex = isRight ? posIndex + 1 : posIndex - 1
    const newOffsetLeft = scrollContentRef.current.children[newIndex].offsetLeft
    scrollContentRef.current.style.transform = `translateX(-${newOffsetLeft}px)`
    // 记录当前的滚动Index
    setPosIndex(newIndex)
    // 是否继续显示right按钮
    setShowRight(totalDistanceRef.current > newOffsetLeft)
    setShowLeft(newOffsetLeft > 0)
  }
  return (
    <ViewWrapper>
      { 
        showLeft && 
        <div className="control left" onClick={e => handleTranslate(false)}>
          <IconArrowLeft />
        </div> 
      }
      { 
        showRight && 
        <div className="control right" onClick={e => handleTranslate(true)}>
          <IconArrowRight />
        </div> 
      }
      <div className="scroll">
        <div className="scroll-content" ref={scrollContentRef}>
          { props.children }
        </div>
      </div>
    </ViewWrapper>
  )
})

export default ScrollView